package com.example.first;

import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.SimpleAdapter;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class RateListActivity3 extends AppCompatActivity implements AdapterView.OnItemClickListener,AdapterView.OnItemLongClickListener,Runnable {
    Handler handler;
    String TAG = "RateListActivity3";
    GridView gridView;//换成Gridview
    MyAdapter adapter;
    SimpleAdapter listItemAdapter;
    List<HashMap<String, String>> list;
    private String logDate = "";
    private final String DATE_SP_KEY = "lastRateDateStr";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rate_list3);

        SharedPreferences sp = getSharedPreferences("myrate", Context.MODE_PRIVATE);
        logDate = sp.getString(DATE_SP_KEY, "");
        Log.i(TAG, "onCreate: lastRateDateStr" + logDate);

        handler = new Handler(Looper.myLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == 5) {
                    list = (List<HashMap<String, String>>) msg.obj;
                    listItemAdapter = new SimpleAdapter(RateListActivity3.this, list,
                            R.layout.list_item,
                            new String[]{"cname", "cval"},
                            new int[]{R.id.title1, R.id.detail});
                    gridView = findViewById(R.id.mylist2);
                    gridView.setAdapter(listItemAdapter);
                    //adapter = new MyAdapter(RateListActivity3.this,R.layout.list_item,list);
                    //list_item为行布局，里面不出现listview控件
                    //gridView.setAdapter(adapter);
                    gridView.setOnItemClickListener(RateListActivity3.this);
                    gridView.setOnItemLongClickListener(RateListActivity3.this);
                }
                super.handleMessage(msg);
            }
        };
        //开启线程
        //MyTask mytask = new MyTask();
        //mytask.setHandler(handler);
        Thread t = new Thread(this);
        t.start();
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        Log.i(TAG, "onItemClick:...");
        HashMap<String, String> map = (HashMap<String, String>) gridView.getItemAtPosition(position);
        Log.i(TAG, "onItemClick: cname:" + map.get("cname"));
        Log.i(TAG, "onItemClick: cval:" + map.get("cval"));
//        Log.i(TAG, "onItemClick: 打开新窗口");
//        Intent intent= new Intent(this,Calculate.class);
//        intent.putExtra("type",map.get("cname"));
//        intent.putExtra("rate",map.get("cval"));
//        startActivity(intent);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示")
                .setMessage("请确认是否删除当前数据")
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Log.i(TAG, "onClick: 对话框事件处理");
                        list.remove(position);
                        listItemAdapter.notifyDataSetChanged();//更新适配器
                    }
                }).setNegativeButton("否", null);//注意不是positivebutton
        builder.create().show();
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) {
        Log.i(TAG, "onItemLongClick:pos= " + position);
        //adapter.remove(list.getItemAtPosition(position));
        //数组元素不能删除，数组大小不可变

        return true;//屏蔽掉与单击的区别
    }

    @Override
    public void run() {
        Log.i("List", "run...");
        List<String> retList = new ArrayList<String>();
        Message msg = handler.obtainMessage(5);
        String curDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
        Log.i("run", "curDateStr:" + curDateStr + " logDate:" + logDate);
        if (curDateStr.equals(logDate)) {
            //如果相等，则不从网络中获取数据
            Log.i("run", "日期相等，从数据库中获取数据");
            DBManager dbManager = new DBManager(RateListActivity3.this);
            for (RateItem rateItem : dbManager.listAll()) {
                retList.add(rateItem.getCurName() + "=>" + rateItem.getCurRate());
            }
        } else {
            Log.i("run", "日期相等，从网络中获取在线数据");
            //获取网络数据
            try {
                List<RateItem> rateList = new ArrayList<RateItem>();
                Document doc = Jsoup.connect("https://www.boc.cn/sourcedb/whpj/").get();
                Elements tables = doc.getElementsByTag("table");
                Elements trs = tables.get(1).getElementsByTag("tr");
                trs.remove(0);
                for (Element tr : trs) {
                    Elements tds = tr.getElementsByTag("td");
                    if (tds.size() > 0) {
                        Element td1 = tds.first();
                        Element td2 = tds.get(5);
                        String str1 = td1.text();
                        String str2 = td2.text();
                        Log.i(TAG, "run:" + str1 + "==>" + str2);
                        retList.add(str1+ "==>" + str2);
                        RateItem rateItem = new RateItem(str1,str2);
                        rateList.add(rateItem);
                    }
                    DBManager dbManager = new DBManager(RateListActivity3.this);
                    dbManager.deleteAll();
                    Log.i("db","删除所有记录");
                    dbManager.addAll(rateList);
                    Log.i("db","添加新记录集");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            SharedPreferences sp = getSharedPreferences("myrate", Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sp.edit();
            edit.putString(DATE_SP_KEY, curDateStr);
            edit.commit();
            Log.i("run","更新日期结束：" + curDateStr);
        }

         //发送消息
        msg.obj = retList;
        handler.sendMessage(msg);
        Log.i(TAG, "run:sendMessage");
    }
}